import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-bwic-list',
  templateUrl: './bwic-list.component.html',
  styleUrls: ['./bwic-list.component.css']
})
export class BwicListComponent implements OnInit {
  username: string = '';
  identity: string = ''; // 用户身份
  bwicList: any[] = []; // 原始表格数据
  filteredBwicList: any[] = []; // 筛选后的表格数据
  filterOption: string = 'all'; // 筛选选项，默认显示所有条目
  userBids: any[] = []; // 用户竞价信息
  winners: { [cusip: string]: string } = {}; // 存储赢家信息，键为 Cusip，值为用户名
  selectedBid: any = null; // 当前选中的竞价条目

  constructor(private authService: AuthService, private http: HttpClient) {}

  ngOnInit(): void {
    // 获取当前用户的用户名和身份
    const accountInfo = this.authService.getAccountInfo();
    if (accountInfo) {
      this.username = accountInfo.username;
      this.identity = accountInfo.identity;
    }

    // 获取表格数据
    this.fetchBwicList();

    // 获取用户竞价信息
    this.fetchUserBids();
  }

  fetchBwicList(): void {
    // 模拟从后端获取表格数据
    this.bwicList = [
      {
        cusip: '123456789',
        dueDate: '2023-12-31',
        position: 1000,
        marketPrice: 5000,
        startingPrice: 4500,
        bidNumber: '-' // 初始值为 "-"
      },
      {
        cusip: '987654321',
        dueDate: '2026-06-30',
        position: 2000,
        marketPrice: 10000,
        startingPrice: 9500,
        bidNumber: 'BID001'
      },
      {
        cusip: '456789123',
        dueDate: '2027-03-15',
        position: 1500,
        marketPrice: 7500,
        startingPrice: 7000,
        bidNumber: 'BID002'
      },
      {
        cusip: '654321987',
        dueDate: '2028-01-01',
        position: 500,
        marketPrice: 3000,
        startingPrice: 2800,
        bidNumber: 'BID004'
      },
      {
        cusip: '111222333', // 新增测试条目
        dueDate: '2025-12-31',
        position: 800,
        marketPrice: 6000,
        startingPrice: 5500,
        bidNumber: '-' // 初始值为 "-"，表示尚未参与竞价
      }
    ];

    // 初始化筛选后的数据
    this.applyFilter();

    // 获取赢家信息
    this.fetchWinners();
  }

  fetchUserBids(): void {
    // 模拟已参与竞价的测试条目
    this.userBids = [
      {
        cusip: '123456789',
        rank: 1,
        bidAmount: 4800,
        username: 'buyer1'
      },
      {
        cusip: '987654321',
        rank: 2,
        bidAmount: 9700,
        username: 'buyer2'
      }
    ];
  }

  fetchWinners(): void {
    // 模拟从后端获取赢家信息
    this.bwicList.forEach(item => {
      this.http.get<{ username: string }>(`/api/winner?cusip=${item.cusip}`).subscribe(
        response => {
          this.winners[item.cusip] = response.username; // 将赢家信息存储到 winners 对象中
        },
        error => {
          console.error(`获取赢家信息失败 (Cusip: ${item.cusip})`, error);
          this.winners[item.cusip] = '无赢家'; // 如果请求失败，设置默认值
        }
      );
    });
  }

  participateInBidding(item: any): void {
    if (this.identity === '买方客户') {
      // 随机分配竞价号
      const randomBidNumber = `BID${Math.floor(Math.random() * 1000).toString().padStart(3, '0')}`;
      item.bidNumber = randomBidNumber;
      alert(`参与竞价成功！分配的竞价号为：${randomBidNumber}`);
    }
  }

  isExpired(dueDate: string): boolean {
    const currentDate = new Date();
    const dueDateObj = new Date(dueDate);
    return currentDate > dueDateObj;
  }

  applyFilter(): void {
    if (this.filterOption === 'all') {
      this.filteredBwicList = this.bwicList;
    } else if (this.filterOption === 'participated') {
      this.filteredBwicList = this.bwicList.filter(item => item.bidNumber !== '-');
    } else if (this.filterOption === 'expired') {
      this.filteredBwicList = this.bwicList.filter(item => this.isExpired(item.dueDate));
    }
  }

  onFilterChange(option: string): void {
    this.filterOption = option;
    this.applyFilter();
  }

  getWinner(cusip: string): string {
    return this.winners[cusip] || '无赢家';
  }

  openAddBidModal(item: any): void {
    this.selectedBid = item; // 设置选中的竞价条目
  }
}
